import base64
from PIL import Image
from io import BytesIO
import cv2
import os
import random
import pyautogui
import time


# 滑块的缺口距离识别
def get_distance():
    # 读取背景图片和模板图片
    background = cv2.imread('img/target.png', 0)
    template = cv2.imread('img/target2.png', 0)
    # 进行预处理，如去噪和边缘增强
    template = cv2.Canny(template, 300, 500, 3)
    # 使用算法进行匹配
    res = cv2.matchTemplate(background, template, cv2.TM_CCOEFF)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = max_loc
    distance = top_left[0] * 344 / 552
    return distance


def saveimg(page):
    iframe = page.get_frame('t:iframe')
    iframe('#captcha-verify_img_slide').save(path="./img", name="target2.png", rename=False)
    iframe.ele('#captcha_verify_image').save(path="./img", name="target.png", rename=False)


def slider_img(page):
    while page.get_frame('t:iframe', timeout=3):
        saveimg(page)
        pyautogui.FAILSAFE = False
        script_js = os.path.join('./img/slider.png')
        location = pyautogui.locateOnScreen(script_js, confidence=0.8)  # confidence=0.8
        center_x, center_y = pyautogui.center(location)
        # 模拟自然鼠标移动到输入框位置
        pyautogui.moveTo(center_x, center_y, duration=random.uniform(0.5, 1.5), tween=pyautogui.easeInOutQuad)
        duration = random.uniform(0.5, 1)  # 总持续时间
        steps = int(20 * duration)  # 根据持续时间决定步数
        # 按下鼠标左键准备拖动
        pyautogui.mouseDown(center_x, center_y, button='left')
        x = get_distance()
        print('滑动的距离---', x)
        for i in range(steps):
            # 计算下一步的位置
            step_x = x / steps
            step_y = 2 / steps
            new_x = center_x + step_x * (i + 1)
            new_y = center_y + step_y * (i + 1)
            # 加入随机抖动
            jitter_x = random.uniform(-3, 3)  # 抖动的范围
            jitter_y = random.uniform(-3, 3)
            pyautogui.moveTo(new_x + jitter_x, new_y + jitter_y, duration=duration / steps)
        # 释放鼠标左键结束拖动
        pyautogui.mouseUp(button='left')
        time.sleep(5)
